package com.yanqu.road.web.controller.usercenter.newadmin;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yanqu.road.dao.impl.admin.AdminCommonDaoImpl;
import com.yanqu.road.entity.admin.AdminResult;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.property.Property;
import com.yanqu.road.utils.property.PropertyHelper;
import com.yanqu.road.utils.string.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigInteger;
import java.util.*;

/**
 * 10.兑换码
 */
@RestController
@RequestMapping("/usercenter/admin")
public class CentertExchangeCodeConfigController {

    /**
     * 10.1 兑换码新增
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/add", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String addExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int batchId = jsonObject.getIntValue("batchId");
        //1 通码；2 动态码
        int codeType = jsonObject.getIntValue("codeType");
        String codeName = jsonObject.getString("codeName");
        JSONArray channelId = jsonObject.getJSONArray("channelId");

        //通用码
        String rmakeCode = "";
        if(jsonObject.containsKey("rmakeCode")){
            rmakeCode = jsonObject.getString("rmakeCode");
            if(rmakeCode == null){
                rmakeCode = "";
            }
        }
        //可用次数
        int availableFrequency = jsonObject.getIntValue("availableFrequency");
        //生成數
        int number = jsonObject.getIntValue("number");
        String beginTime = jsonObject.getString("beginTime");
        String endTime = jsonObject.getString("endTime");
        int isNew = jsonObject.getIntValue("isNew");
        int gameType = 0;
        if(jsonObject.containsKey("gameType")) {
            gameType = jsonObject.getIntValue("gameType");
        }
        JSONArray props = jsonObject.getJSONArray("props");

        Property awards = new Property();
        for (int i = 0; i < props.size(); i++) {
            JSONObject object = props.getJSONObject(i);
            awards.addProperty(object.getIntValue("propId"), object.getLongValue("num"));
        }

        List<Integer> channelIdList = new ArrayList<>();
        for (int i = 0; i < channelId.size(); i++) {
            channelIdList.add(channelId.getIntValue(i));
        }
        channelIdList.sort(Integer::compareTo);

        List<Integer> appIdList = new ArrayList<>();
        if(jsonObject.containsKey("appId")){
            JSONArray appId = jsonObject.getJSONArray("appId");
            if(appId != null){
                for (int i = 0; i < appId.size(); i++) {
                    appIdList.add(appId.getIntValue(i));
                }
            }
        }
        //t_s_exchange_code_list 兑换码序列
        //t_s_exchange_code_conf 兑换码配置
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("batch", batchId);
        dataMap.put("codeType", codeType);
        dataMap.put("name", codeName);
        dataMap.put("channelId", StringUtils.listToString(channelIdList, ","));
        dataMap.put("appId", StringUtils.listToString(appIdList, ","));
        //通用码
        dataMap.put("surrCode", rmakeCode);
        dataMap.put("startTime", DateHelper.getString2Date(beginTime));
        dataMap.put("endTime", DateHelper.getString2Date(endTime));
        //最大上限：
        dataMap.put("maxLimit", number);
        //领取次数：
        dataMap.put("receiveNum", availableFrequency);
        dataMap.put("awards", PropertyHelper.parsePropertyToString(awards));
        dataMap.put("gameType", gameType);

        if(isNew == 1){
            //新增
           int newId = new AdminCommonDaoImpl().addExchangeCodeConfig(dataMap, false);
           if(newId <= 0){
               return AdminResult.failMsg("新增兑换码配置失败").toJsonString();
           }
            List<Map<String, Object>> codeList = new ArrayList<>();
            if(codeType == 1){
                Map<String, Object> map = new HashMap<>();
                map.put("exchangeCode", rmakeCode);
                map.put("configId", newId);
                map.put("batch", batchId);
                map.put("codeNum", 0);
                map.put("randNum", 0);
                codeList.add(map);

                boolean b = new AdminCommonDaoImpl().addBatchExchangeCode(codeList, false);
                if(!b){
                    return AdminResult.failMsg("新增失败").toJsonString();
                }
            }else {
                //动态码
                //动态码规则
                long num = System.currentTimeMillis();
                Sqids.Builder builder = Sqids.builder();
                Sqids sqids = builder.minLength(12).build();
                for (int i = 1; i <= number; i++) {
                    String exchangeCode = sqids.encode(Collections.singletonList(num + i));
                    Map<String, Object> map = new HashMap<>();
                    map.put("exchangeCode", exchangeCode);
                    map.put("configId", newId);
                    map.put("batch", batchId);
                    map.put("codeNum", 0);
                    map.put("randNum", 0);
                    codeList.add(map);
                    if(i % 1000 == 0){
                        boolean b = new AdminCommonDaoImpl().addBatchExchangeCode(codeList, false);
                        if(!b){
                            return AdminResult.failMsg("新增失败").toJsonString();
                        }
                        codeList.clear();
                    }
                }
                if(!codeList.isEmpty()){
                    boolean b = new AdminCommonDaoImpl().addBatchExchangeCode(codeList, false);
                    if(!b){
                        return AdminResult.failMsg("新增失败").toJsonString();
                    }
                }
            }
        }else {
            //todo 修改
        }
        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 10.2 兑换码查询
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/search", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String searchExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        JSONArray channelId = jsonObject.getJSONArray("channelId");

        List<Integer> channelIdList = new ArrayList<>();
        for (int i = 0; i < channelId.size(); i++) {
            channelIdList.add(channelId.getIntValue(i));
        }
        channelIdList.sort(Integer::compareTo);
        String channelIdStr = StringUtils.listToString(channelIdList, ",");

        int batchId = 0;
        if(jsonObject.containsKey("batchId")){
            batchId = jsonObject.getIntValue("batchId");
        }
        String codeName = "";
        if(jsonObject.containsKey("codeName")){
            codeName = jsonObject.getString("codeName");
        }

        List<Integer> codeType = new ArrayList<>();
        if(jsonObject.containsKey("codeType")){
            JSONArray array = jsonObject.getJSONArray("codeType");
            for (int i = 0; i < array.size(); i++) {
                codeType.add(array.getIntValue(i));
            }
        }

        long beginTime = 0;
        if(jsonObject.containsKey("beginTime")){
            beginTime = DateHelper.str2timestamp(jsonObject.getString("beginTime")) / 1000;
        }
        long endTime = 0;
        if(jsonObject.containsKey("endTime")){
            endTime = DateHelper.str2timestamp(jsonObject.getString("endTime")) / 1000;
        }

        //状态 1 有效；2 冻结；3 耗尽；4 过期
        int state = jsonObject.getIntValue("state");

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");

        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        List<Integer> searchList = new ArrayList<>();
        List<Integer> matchIdList = new ArrayList<>();
        List<Map<String, Object>> dataList;
        if(batchId > 0){
            dataList =  new AdminCommonDaoImpl().getExchangeCodeConfig2(channelIdStr, batchId, false);
        }else {
            dataList =  new AdminCommonDaoImpl().getExchangeCodeConfig(channelIdStr, false);
        }
        for (Map<String, Object> objectMap : dataList) {
            if(batchId > 0){
                if(batchId != (int) objectMap.get("batchId")){
                    continue;
                }
            }
            if(!StringUtils.isNullOrEmpty(codeName)){
                String name = (String) objectMap.get("name");
                if(!name.contains(codeName)){
                    continue;
                }
            }
            if(!codeType.isEmpty()){
                if(!codeType.contains(objectMap.get("codeType"))){
                    continue;
                }
            }
            if(beginTime > 0){
                if(beginTime < (long) objectMap.get("startTime")){
                    continue;
                }
            }
            if(endTime > 0){
                if(endTime > (long) objectMap.get("endTime")){
                    continue;
                }
            }
            //todo state 过滤
            if(state == 2){
                int isEnable = (int)objectMap.get("isEnable");
                if(isEnable == 1){
                    continue;
                }
            }else if(state == 1){
                int isEnable = (int)objectMap.get("isEnable");
                if(isEnable == 0){
                    continue;
                }
            }

            matchIdList.add((int)objectMap.get("id"));
        }

        for (int i = startIndex; i < startIndex + pageSize && i < matchIdList.size(); i++) {
            searchList.add(matchIdList.get(i));
        }

        List<Map<String, Object>> resultList = new AdminCommonDaoImpl().getExchangeCodeConfig(searchList, false);

        AdminResult result = AdminResult.defaultInstance();

        result.getData().put("total", matchIdList.size());

        List<Map<String, Object>> list = new ArrayList<>();
        for (Map<String, Object> data : resultList) {
            Map<String, Object> map = new HashMap<>();
            map.put("batchId", data.get("batch"));
            map.put("channelId", StringUtils.stringToStringList((String)data.get("channelId"), ","));
            map.put("codeName", data.get("name"));
            map.put("codeType", data.get("codeType"));
            map.put("beginTime", DateHelper.date2String((Date)data.get("beginTime")));
            map.put("endTime", DateHelper.date2String((Date)data.get("endTime")));
            map.put("state", data.get("isEnable"));
            map.put("availableFrequency", data.get("receiveNum"));
            map.put("number", data.get("maxGenerate"));
            map.put("useNumber", data.get("exportNum"));
            Property reward = PropertyHelper.parseStringToProperty((String)data.get("awards"));
            List<Map<String, Object>> propMapList = new ArrayList<>();
            for (Map.Entry<Integer, BigInteger> entry : reward.getGoods().entrySet()) {
                Map<String, Object> propMap = new HashMap<>();
                propMap.put("propId", entry.getKey());
                propMap.put("num", entry.getValue().longValue());
                propMapList.add(propMap);
            }
            map.put("props", propMapList);
            map.put("gameType", data.get("gameType"));
            map.put("appid", StringUtils.stringToStringList((String)data.get("appId"), ","));
            map.put("id", data.get("id"));
            map.put("rmakeCode", data.get("exchangeCode"));
            list.add(map);
        }
        result.getData().put("row", list);

        return result.toJsonString();
    }

    /**
     * 10.3 兑换码冻结
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/freeze", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String freezeExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("batchId") || !jsonObject.containsKey("state")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }

        int batchId = jsonObject.getIntValue("batchId");
        int state = jsonObject.getIntValue("state");

        boolean b = new AdminCommonDaoImpl().updateExchangeCodeState(batchId, state);
        if(!b){
            return AdminResult.failMsg("操作失败").toJsonString();
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 10.4 兑换码追加
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/append", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String appendExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("batchId") || !jsonObject.containsKey("number")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }

        int batchId = jsonObject.getIntValue("batchId");
        List<Map<String, Object>> list = new AdminCommonDaoImpl().getExchangeCodeConfig(batchId, false);
        if(list.isEmpty()){
            return AdminResult.failMsg("批次不存在").toJsonString();
        }

        Map<String, Object> objectMap = list.get(0);
        int configId = (int)objectMap.get("id");

        int number = jsonObject.getIntValue("number");

        List<Map<String, Object>> codeList = new ArrayList<>();
        long num = System.currentTimeMillis();
        Sqids.Builder builder = Sqids.builder();
        Sqids sqids = builder.minLength(12).build();
        for (int i = 1; i <= number; i++) {
            String exchangeCode = sqids.encode(Collections.singletonList(num + i));
            Map<String, Object> map = new HashMap<>();
            map.put("exchangeCode", exchangeCode);
            map.put("configId", configId);
            map.put("batch", batchId);
            map.put("codeNum", 0);
            map.put("randNum", 0);
            codeList.add(map);
            if(i % 1000 == 0){
                boolean b = new AdminCommonDaoImpl().addBatchExchangeCode(codeList, false);
                if(!b){
                    return AdminResult.failMsg("追加失败").toJsonString();
                }
                codeList.clear();
            }
        }
        if(!codeList.isEmpty()){
            boolean b = new AdminCommonDaoImpl().addBatchExchangeCode(codeList, false);
            if(!b){
                return AdminResult.failMsg("追加失败").toJsonString();
            }
        }

        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 10.5 兑换码用户列表
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/userList", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String userListExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int batchId = jsonObject.getIntValue("batchId");

        int pageNum = jsonObject.getIntValue("pageNum");
        int pageSize = jsonObject.getIntValue("pageSize");

        int startIndex = (pageNum - 1) * pageSize;
        startIndex = Math.max(0, startIndex);

        long playerId = 0;
        if(jsonObject.containsKey("playerId")){
            playerId = jsonObject.getLongValue("playerId");
        }

        String exchangeCode = "";
        if(jsonObject.containsKey("exchangeCode")){
            exchangeCode = jsonObject.getString("exchangeCode");
            if("null".equals(exchangeCode)){
                exchangeCode = "";
            }
        }

        List<Map<String, Object>> dataList = new AdminCommonDaoImpl().getExchangeCodeUser(batchId);

        List<Map<String, Object>> searchList = new ArrayList<>();
        List<Map<String, Object>> matchIdList = new ArrayList<>();

        for (Map<String, Object> objectMap : dataList) {
            if(!StringUtils.isNullOrEmpty(exchangeCode)){
                if(!exchangeCode.equals(objectMap.get("code"))){
                    continue;
                }
            }
            if(playerId > 0){
                if(playerId != (long)objectMap.get("userId")){
                    continue;
                }
            }
            matchIdList.add(objectMap);
        }

        for (int i = startIndex; i < startIndex + pageSize && i < matchIdList.size(); i++) {
            searchList.add(matchIdList.get(i));
        }

        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("total", searchList.size());
        result.getData().put("row", searchList);
        return result.toJsonString();
    }

    /**
     * 10.6兑换码导出
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/export", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String exportExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        int batchId = jsonObject.getIntValue("batchId");

        List<Map<String, Object>> dataList = new AdminCommonDaoImpl().getExchangeCodeUser(batchId);

        int type = jsonObject.getIntValue("type");

        if(type != 3){
            Iterator<Map<String, Object>> iterator = dataList.iterator();
            while (iterator.hasNext()){
                Map<String, Object> next = iterator.next();
                long userId = (long)next.get("userId");
                if(type == 1 && userId == 0){
                    iterator.remove();
                }else if(type == 2 && userId > 0){
                    iterator.remove();
                }
            }
        }
        StringBuilder builder = new StringBuilder();
        builder.append("batch");
        builder.append(",");
        builder.append("code");
        builder.append(",");
        builder.append("userId");
        builder.append(",");
        builder.append("receiveTime");
        builder.append("\n");
        for (Map<String, Object> map : dataList) {
            builder.append(map.get("batch"));
            builder.append(",");
            builder.append(map.get("code"));
            builder.append(",");
            builder.append(map.get("userId"));
            builder.append(",");
            builder.append(map.get("receiveTime"));
            builder.append("\n");
        }
//        AdminResult result = AdminResult.defaultInstance();
//        result.getData().put("total", dataList.size());
//        result.getData().put("row", dataList);
//
//        return result.toJsonString();
        return builder.toString();
    }

    /**
     * 10.7兑换码生成上限-主要针对动态码
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/upperLimit", method = RequestMethod.GET, produces = {"application/json;charset=UTF-8"})
    public String upperLimitExchangeCode(HttpServletRequest request) {
        AdminResult result = AdminResult.defaultInstance();
        result.getData().put("num", 10000);
        return result.toJsonString();
    }

    /**
     * 10.8兑换码追加批次详情
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/batchDetail", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String batchDetailExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        if(!jsonObject.containsKey("batchId")){
            return AdminResult.failMsg("参数缺失").toJsonString();
        }



        return AdminResult.defaultInstance().toJsonString();
    }

    /**
     * 10.9 查询通码是否已经存在
     */
    @ResponseBody
    @RequestMapping(value = "exchangeCode/checkExist", method = RequestMethod.POST, produces = {"application/json;charset=UTF-8"})
    public String checkExistExchangeCode(HttpServletRequest request, @RequestBody JSONObject jsonObject) {

        String rmakeCode = jsonObject.getString("rmakeCode");

        boolean existExchangeCode = new AdminCommonDaoImpl().isExistExchangeCode(rmakeCode, false);
        if(!existExchangeCode){
            return AdminResult.defaultInstance().toJsonString();
        }
        return AdminResult.failMsg("兑换码存在").toJsonString();
    }
}
